package com.william.jdbcplus.core.dialects.ddl.pk.impl;

import com.william.jdbcplus.core.metadata.TableHelperUtil;
import com.william.jdbcplus.core.metadata.TableInfo;
import com.william.jdbcplus.core.metadata.TablePkInfo;
import com.william.jdbcplus.common.entity.Entity;
import com.william.jdbcplus.core.dialects.ddl.pk.IPk;
import com.william.jdbcplus.core.toolkit.StringPool;
import com.william.jdbcplus.core.util.datameta.TableMetaPkInfo;

public class OraclePk implements IPk {
    /**
     * 新增主键
     *
     * @param clazz
     * @return
     */
    @Override
    public <M extends Entity> String add(Class<M> clazz, TablePkInfo pkInfo) {
        TableInfo tableInfo = TableHelperUtil.getTableInfo(clazz);
        StringBuffer sqlBuffer = new StringBuffer();
        sqlBuffer.append("alter table " + tableInfo.getTableName() + " add constraint " + pkInfo.getShortPkName() + " primary key(" + pkInfo.getPkColumn() + ");");
        return sqlBuffer.toString();
    }

    /**
     * 修改主键
     *
     * @param clazz
     * @param pkInfo
     * @return
     */
    @Override
    public <M extends Entity> String modify(Class<M> clazz, TablePkInfo pkInfo) {
        StringBuffer sqlBuffer = new StringBuffer();
        sqlBuffer.append(drop(clazz, pkInfo))
                .append(StringPool.NEWLINE)
                .append(add(clazz, pkInfo));
        return sqlBuffer.toString();
    }

    /**
     * 删除主键
     *
     * @param clazz
     * @return
     */
    @Override
    public <M extends Entity> String drop(Class<M> clazz, TablePkInfo pkInfo) {
        TableInfo tableInfo = TableHelperUtil.getTableInfo(clazz);
        StringBuffer sqlBuffer = new StringBuffer();
        sqlBuffer.append("alter table " + tableInfo.getTableName() + " drop primary key;");
        return sqlBuffer.toString();
    }

    /**
     * 检查是否与数据库一致
     *
     * @param clazz
     * @param pkInfo
     * @param metaPkInfo
     */
    @Override
    public <M extends Entity> Boolean match(Class<M> clazz, TablePkInfo pkInfo, TableMetaPkInfo metaPkInfo) {
        // 主键列不一样，返回不匹配
        if (!pkInfo.getPkColumn().equalsIgnoreCase(metaPkInfo.getColumnName())) {
            return false;
        }

        return true;
    }
}
